package yx.service;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import yx.dao.BaseDaoInt;
import yx.model.BsCorporation;
import yx.model.BsStudent;
import yx.model.SmCode;
import yx.utils.FileUtils;
import yx.vo.DatagridVO;
import yx.vo.StudentVO;

@Service("studentService")
public class StudentServiceImpl implements StudentServiceInt {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(StudentServiceImpl.class);

	private BaseDaoInt<BsStudent> studentDao;
	private BaseDaoInt<BsCorporation> corporationDao;
	private BaseDaoInt<SmCode> codeDao;

	public BaseDaoInt<BsStudent> getStudentDao() {
		return studentDao;
	}

	@Autowired
	public void setStudentDao(BaseDaoInt<BsStudent> studentDao) {
		this.studentDao = studentDao;
	}

	public BaseDaoInt<BsCorporation> getCorporationDao() {
		return corporationDao;
	}

	@Autowired
	public void setCorporationDao(BaseDaoInt<BsCorporation> corporationDao) {
		this.corporationDao = corporationDao;
	}

	public BaseDaoInt<SmCode> getCodeDao() {
		return codeDao;
	}

	@Autowired
	public void setCodeDao(BaseDaoInt<SmCode> codeDao) {
		this.codeDao = codeDao;
	}

	@Override
	public StudentVO save(StudentVO student) {
		BsStudent t = new BsStudent();
		BeanUtils.copyProperties(student, t);

		studentDao.save(t);
		BeanUtils.copyProperties(t, student);

		// 性别转换
		if (student.getGender() != null && !"".equals(student.getGender())) {
			Map<String, String> retMap = getStudentGenderMap("02");
			student.setGenderName(retMap.get(student.getGender()));
		}

		// 单位
		if (student.getCorporationId() != null && !"".equals(student.getCorporationId())) {
			BsCorporation corp = corporationDao.get(BsCorporation.class, student.getCorporationId());
			student.setCorporationName(corp.getCorporationName());
		}
		return student;
	}
	
	@Override
	public void saveAll(List<BsStudent> list) {
		for(BsStudent stu : list){
			studentDao.save(stu);
		}
	}

	@Override
	public DatagridVO datagrid(StudentVO student) {
		DatagridVO dg = new DatagridVO();
		String hql = "from BsStudent t where 1 = 1";
		Map<String, Object> params = new HashMap<String, Object>();
		hql = addWhere(student, hql, params);
		String totalHql = "select count(*) " + hql;
		hql = addOrder(student, hql);
		List<BsStudent> l = studentDao.find(hql, params, student.getPage(), student.getRows());
		List<StudentVO> nl = new ArrayList<StudentVO>();
		changeModel(l, nl);
		dg.setTotal(studentDao.count(totalHql, params));
		dg.setRows(nl);
		return dg;
	}

	private void changeModel(List<BsStudent> l, List<StudentVO> nl) {
		if (l != null && l.size() > 0) {

			// 获得单位
			Map<Integer, String> corpMap = new HashMap<Integer, String>();
			List<String> corplist = new ArrayList<String>();
			for (BsStudent stu : l) {
				if (stu.getCorporationId() != null) {
					if (!corplist.contains(stu.getCorporationId().toString())) {
						corplist.add(stu.getCorporationId().toString());
					}
				}
			}
			String temp = null;
			if (corplist != null && corplist.size() != 0) {
				temp = StringUtils.join(corplist, "','");
			}
			if (temp != null) {
				List<BsCorporation> dbCorpList = corporationDao.find(" from BsCorporation t where t.id in ('" + temp + "')");
				for (BsCorporation corp : dbCorpList) {
					corpMap.put(corp.getId(), corp.getCorporationName());
				}
			}

			// 获得性别的名值对
			Map<String, String> genderMap = getStudentGenderMap("02");

			for (BsStudent t : l) {
				StudentVO u = new StudentVO();
				BeanUtils.copyProperties(t, u);
				if (t.getCorporationId() != null && !"".equals(t.getCorporationId())) {
					if (!corpMap.isEmpty()) {
						String n = corpMap.get(t.getCorporationId());
						if (n != null && !"".equals(n)) {
							u.setCorporationName(n);
						}
					}
				}

				// 性别转换
				if (t.getGender() != null && !"".equals(t.getGender())) {
					u.setGenderName(genderMap.get(t.getGender()));
				}
				nl.add(u);
			}
		}
	}

	private String addOrder(StudentVO student, String hql) {
		if (student.getSort() != null || student.getOrder() != null) {
			hql += " order by " + student.getSort() + " " + student.getOrder();
		}
		return hql;
	}

	private String addWhere(StudentVO student, String hql, Map<String, Object> params) {
		if (student.getStudentName() != null && !"".equals(student.getStudentName().trim())) {
			hql += " and t.studentName like :studentName";
			params.put("studentName", "%%" + student.getStudentName().trim() + "%%");
		}
		if (student.getStudentNo() != null && !"".equals(student.getStudentNo().trim())) {
			hql += " and t.studentNo = :studentNo";
			params.put("studentNo", student.getStudentNo().trim());
		}
		if (student.getMobile() != null && !"".equals(student.getMobile().trim())) {
			hql += " and t.mobile = :mobile";
			params.put("mobile", student.getMobile().trim());
		}
		if (student.getEmail() != null && !"".equals(student.getEmail().trim())) {
			hql += " and t.email = :email";
			params.put("email", student.getEmail().trim());
		}
		return hql;
	}

	@Override
	public void remove(String ids) {
		String[] nids = ids.split(",");
		String hql = "delete BsStudent t where t.id in (";
		for (int i = 0; i < nids.length; i++) {
			if (i > 0) {
				hql += ",";
			}
			hql += "'" + nids[i] + "'";
		}
		hql += ")";
		studentDao.executeHql(hql);
	}

	@Override
	public StudentVO edit(StudentVO student) {
		BsStudent stu = studentDao.get(BsStudent.class, student.getId());
		
		// 只更新学生基本信息
		stu.setStudentNo(student.getStudentNo());
		stu.setStudentName(student.getStudentName());
		stu.setGender(student.getGender());
		stu.setTitle(student.getTitle());
		stu.setCorporationId(student.getCorporationId());
		stu.setPosition(student.getPosition());
		stu.setMobile(student.getMobile());
		stu.setEmail(student.getEmail());
		stu.setQq(student.getQq());
		stu.setPhone(student.getPhone());
		stu.setFax(student.getFax());

		// 性别转换
		if (student.getGender() != null && !"".equals(student.getGender())) {
			Map<String, String> retMap = getStudentGenderMap("02");
			student.setGenderName(retMap.get(student.getGender()));
		}

		// 单位
		if (student.getCorporationId() != null && !"".equals(student.getCorporationId())) {
			BsCorporation corp = corporationDao.get(BsCorporation.class, student.getCorporationId());
			student.setCorporationName(corp.getCorporationName());
		}
		return student;
	}

	@Override
	public StudentVO queryStudent(StudentVO student) {
		BsStudent t = studentDao.get(BsStudent.class, student.getId());
		BeanUtils.copyProperties(t, student);
		return student;
	}
	
	@Override
	public List<StudentVO> queryStudentByNameAndNo(String studentName, String studentNo) {
		String hql = "from BsStudent s where s.studentName = :studentName and s.studentNo = :studentNo";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("studentName", studentName);
		params.put("studentNo", studentNo);
		List<BsStudent> list = studentDao.find(hql,params);
		List<StudentVO> retList = new ArrayList<StudentVO>();
		if(list != null && list.size() != 0){
			for (BsStudent t : list) {
				StudentVO u = new StudentVO();
				BeanUtils.copyProperties(t, u);
				retList.add(u);
			}
		}
		return retList;
	}

	private Map<String, String> getStudentGenderMap(String type) {
		Map<String, String> retMap = new HashMap<String, String>();
		if (type != null && !"".equals(type)) {
			String hql = "from SmCode t where t.ctype = :ctype";
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("ctype", type);
			List<SmCode> l = codeDao.find(hql, params);
			for (SmCode c : l) {
				retMap.put(c.getCvalue(), c.getCname());
			}
		}
		return retMap;
	}
	
	/**
	 * 获得文件字节
	 */
	public byte[] getFileBytes(String fullFilePath) {
		if (fullFilePath == null || "".equals(fullFilePath)) {
			logger.info("指定的文件不存在！");
			return new byte[] {};
		}
		File file = new File(fullFilePath);
		if (!file.exists()) {
			logger.info("指定的文件不存在！");
			return new byte[] {};
		}
		return FileUtils.readFile(file);
	}
}
